import axios from 'axios'
// import {Notice, Message} from 'iview';
import store from '@/store'
import storage from '@/common/store'
import router from '@/router';
import VueCookies from 'vue-cookies'
const qs = require('qs')
import api from '@/api/index'
// axios基本配置
axios.defaults.timeout = 50000
axios.defaults.withCredentials = true;//让ajax携带cookie

// http request 拦截器
axios.interceptors.request.use(config => {
    // if (store.state.auth_info) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
    //     config.headers['token'] = `${store.state.auth_info.token}`;
    // }
    // const cookie = VueCookies.get('campus_token'); //获取Cookie
    const campus_token = storage.getItem('campus_token'); //获取Cookie
    // alert(JSON.stringify(campus_token))
    config.headers = {
        'Content-Type': 'application/x-www-form-urlencoded', //设置跨域头部
        'campus-token':campus_token
    };
    // if (cookie) {
    //     config.params = { 'cookie': cookie } //后台接收的参数，后面我们将说明后台如何接收
    // }
    // alert(JSON.stringify(config))
    return config;
}, err => {
    // console.log("err",err);
    return Promise.reject(err)
}
)

// http response 拦截器
axios.interceptors.response.use(response => {
    return response.data
}, error => {
    if (error && error.response) {
        // console.log("error:"+error);
        responseError(error);
    }
    return Promise.reject(error)
})

//错误执行提示
const responseError = function (err) {
    switch (err.response.status) {
        case 400:
            // err.message = '400:请求错误'
            break
        case 401:
            // err.message = '401:未授权，请登录'
            break
        case 403:
            // err.message = '503:拒绝访问'
            break
        case 404:
            // err.message = `404:请求地址出错: ${err.response.config.url}`
            break
        case 408:
            // err.message = '408:请求超时'
            break
        case 500:
            // err.message = '500:服务器内部错误'
            break
        case 501:
            err.message = '501:服务未实现'
            break
        case 502:
            err.message = '502:网关错误'
            break
        case 503:
            err.message = '503:服务不可用'
            break
        case 504:
            err.message = '504:网关超时'
            break
        case 505:
            err.message = '505:HTTP版本不受支持'
            break
        default:
    }
    // Notice.error({title: '错误提示',desc: err.message });
}
let tokenLock =false;
let tokenTime=0;
const http = {
    /**
     * post 请求方法
     * @param url
     * @param data
     * @returns {Promise}
     */
    post(url, data) {
        if (!data) data = {};
        // if (storage.getStore('campus_token')) data.campus_token = storage.getStore('campus_token');
        // if (store.state.auth_info) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
        //     data.token = `${store.state.auth_info.token}`;
        //     //config.data.token = `${store.state.auth_info.token}`;
        // }
        return new Promise((resolve, reject) => {
            axios.post(url, qs.stringify(data)).then(response => {
                if (response.code == 200) {
                    // this.$toast(response.message)
                    resolve(response)
                }else if(response.code == 401){
                    // http.checkToken(resolve, reject)
                    this.$toast.fail({message:'登录超时，请重新登录',duration:500});
                    setTimeout(function(){
                        router.push({path:'/login'});
                    },500);
                }else if(response.code == 1){
                    this.$toast.fail({message:'服务器异常,请联系管理员',duration:500});
                }else {
                    this.$toast.fail({message:response.message,duration:500})
                }
            }, err => {
                reject(err)
            })
        })
    },
    /**
     * get 请求方法
     * @param url
     * @param data
     * @returns {Promise}
     */
    get(url, data) {
        let that=this;
        return new Promise((resolve, reject) => {
            axios.get(url, { params: data }).then(response => {
                if (response.code == 200) {
                    // this.$toast(response.message)
                    resolve(response)
                }else if(response.code == 401){
                    // http.checkToken(resolve, reject)

                    that.$toast.fail({message:'登录超时，请重新登录',duration:500});
                    setTimeout(function(){
                        router.push({path:'/login'});
                    },500);
                }else if(response.code == 1){
                    this.$toast.fail({message:'服务器异常,请联系管理员',duration:500});
                }else {
                    this.$toast.fail({message:response.message,duration:500})
                }
            }, err => {
                reject(err)
            })
        })
    },
    /**
     * put 请求方法
     * @param url
     * @param id
     * @param data
     * @returns {Promise}
     */
    put(url, id, data) {
        return new Promise((resolve, reject) => {
            axios.put(url + id, data).then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
        })
    },
    /**
     * delete 请求方法
     * @param url
     * @param id
     * @returns {Promise}
     */
    delete(url, id) {
        return new Promise((resolve, reject) => {
            axios.delete(url + id).then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
        })
    },
    /**
     * post 请求方法  请求类型为application/json
     * @param url
     * @param data
     * @returns {Promise}
     */
    json_post(url, data) {
        if (store.state.auth_info) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
            data.token = `${store.state.auth_info.token}`;
            //config.data.token = `${store.state.auth_info.token}`;
        }
        return new Promise((resolve, reject) => {
            axios.post(url, data, { headers: { 'Content-Type': 'application/json;charset=UTF-8' } }).then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
        })
    },
    files(url, params) {
        // var data = new FormData();
        // for (var key in params) {
        //     console.log(key, params[key])
        //     data.append(key, params[key]);
        // }
        return new Promise((resolve, reject) => {
            axios.post(url, params, { headers: { 'Content-Type': 'multipart/form-data' } }).then(response => {
                if (response.code == 200) {
                    // this.$toast(response.message)
                    resolve(response)
                }else if(response.code == 401){
                    this.$toast.fail({message:'登录超时，请重新登录',duration:500});
                    setTimeout(function(){
                        router.push({path:'/login'});
                    },500);
                }else if(response.code == 1){
                    this.$toast.fail({message:'服务器异常,请联系管理员',duration:500});
                }else {
                    this.$toast.fail({message:response.message,duration:500})
                }
            }, err => {
                reject(err)
            })
        })
    },
    checkToken (resolve, reject) {
        let that=this;
        console.log(api.user.refresh)
        var p = new Promise(function(resolve, reject){
            if(resolve == void(0)) return;
            let m_access_token = storage.getItem('campus_token');
            let refresh_token = storage.getItem('rt');
            
            if(m_access_token){
                resolve();
            }else{
                //正在请求更新token时，其他接口等待
                if(tokenLock&&tokenTime<30){
                    console.log(1)
                    setTimeout(function(){
                        tokenTime++;
                        http.checkToken().then(resolve)
                    },500);
                }else if(tokenTime>30){ //500*30是15S，15s没有响应就直接跳登录页
                    console.log(2)
                    this.$toast.fail({message:'登录超时，请重新登录',duration:500});
                    setTimeout(function(){
                        router.push({path:'/login'});
                    },500);
                    storage.removetItem('campus_token');
                    storage.removetItem('rt');
                }else{
                    var parm={
                        rt:refresh_token,
                        deviceName:'IPhone 8',
                        deviceId:'1231231231231231231231',
                        deviceModel:'IPhone',
                        os:'IOS',
                        osVersion:'12.4',
                        "ts":(new Date()).getTime()
                    }
                    console.log(3)
                    tokenLock = true;
                    axios({
                        method: 'post',
                        url:api.user.refresh,
                        data:qs.stringify(parm)
                    }).then(function(res) {
                        tokenLock = false;
                        tokenTime = 0;
                        storage.setItem('campus_token', res.data.ct);
                        resolve();
                    }).catch(function(error) {
                        reject();
                    });
                }
            }
        });
        return p;
    },
}


export default http
